package com.wswy.wzcx.ui.persenter

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.Rect
import android.graphics.RectF
import android.os.Bundle
import android.os.Parcelable
import android.support.v4.content.ContextCompat
import android.support.v4.graphics.drawable.DrawableCompat
import android.support.v4.view.ViewCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.TextView
import com.che.libcommon.api.BaseResult
import com.che.libcommon.api.ProgressDialogObserver
import com.che.libcommon.recycler.RowFactory
import com.che.libcommon.recycler.RowListAdapter2
import com.che.libcommon.ui.BaseActivity
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.model.home.RouterUtils
import com.wswy.wzcx.model.license.UserCarInfo
import com.wswy.wzcx.module.InternalMsgCodeKt
import com.wswy.wzcx.module.UserDataProvider
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.car.result.QueryResultActivity
import com.wswy.wzcx.ui.component.WZDBComponent
import com.wswy.wzcx.ui.component.WZDBComponent2
import com.wswy.wzcx.ui.other.*
import com.wswy.wzcx.widget.home.RubbishFrameLayout

/**
 * Created by wangduheng26 on 2018/3/28.
 * wangduheng26@gmail.com
 */
class WZDBPresenter(val context: Context) {

    private lateinit var rootLayout: FrameLayout
    lateinit var tvStartAdd: TextView
    lateinit var recycleView: RecyclerView
    lateinit var list: MutableList<Parcelable>
    lateinit var adapter: RowListAdapter2<Parcelable>
    fun onCreate(frameLayout: FrameLayout) {
        rootLayout = frameLayout
        rootLayout.id = ViewHelp.generateViewId()
        val progressBar = ProgressBar(context)
        rootLayout.addView(progressBar, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER))


    }

    private var delegate: CloseDelegate? = null
    fun onActivityCreate(savedInStanceState: Bundle?) {
        if (context is BaseActivity)
            delegate = CloseDelegate(context,InternalMsgCodeKt.UPLOAD_COMPLETE_WDZD)

    }

    fun showEmptyView() {
        rootLayout.removeAllViews()
        val layout = RelativeLayout(context)
        //layout.setBackgroundColor(ContextCompat.getColor(context,R.color.default_bg_color))

        val layout1 = RubbishFrameLayout(context, RubbishFrameLayout.TYPE_JZCF)
        layout1.background=ContextCompat.getDrawable(context,R.drawable.shape_while)
        ViewCompat.setElevation(layout1,AndroidUtilities.dpf2(2f))
        val params = LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 110)
        LayoutHelper.setMargin(params, 15)

        val relativeLayout = RelativeLayout(context)

        val textView = TextView(context)
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f)
        textView.setTextColor(Color.parseColor("#444444"))
        textView.text = "你还没有添加车辆"
        var layoutParams = LayoutHelper.createRelative(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT)
        LayoutHelper.setMargin(layoutParams, 20, 18, 0, 0)
        relativeLayout.addView(textView, layoutParams)


        tvStartAdd = TextView(context)
        tvStartAdd.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
        tvStartAdd.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary))
        tvStartAdd.text = "添加车辆"
        val drawable = ContextCompat.getDrawable(context, R.drawable.arrow_right_grey)?.mutate()
        if (drawable != null) DrawableCompat.setTint(drawable, ContextCompat.getColor(context, R.color.colorPrimary))

        tvStartAdd.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null)
        layoutParams = LayoutHelper.createRelative(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT)
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
        LayoutHelper.setMargin(layoutParams, 0, 0, 20, 16)
        relativeLayout.addView(tvStartAdd, layoutParams)
        LayoutHelper.setSelectable(tvStartAdd)
        tvStartAdd.setOnClickListener {
            clickEmptyLayout(it)
        }
        layout1.addView(relativeLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT))
        layout.addView(layout1, params)
        rootLayout.addView(layout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT))


    }

    private fun clickEmptyLayout(v: View) {

        RouterUtils.startAdd(context)
        //AddEditLicenseActivity.startAdd(context, -1)
    }


    private fun showListLayout(data: List<UserCarInfo>?) {
        rootLayout.removeAllViewsInLayout()
        val layout = FrameLayout(context)
        //layout.setBackgroundColor(ContextCompat.getColor(context, R.color.default_background_color))
        recycleView = RecyclerView(context)
        recycleView.layoutManager = LinearLayoutManager(context)
        recycleView.addItemDecoration(object :android.support.v7.widget.RecyclerView.ItemDecoration(){
            override fun getItemOffsets(outRect: Rect, view: View, parent: android.support.v7.widget.RecyclerView, state: android.support.v7.widget.RecyclerView.State) {
                super.getItemOffsets(outRect, view, parent, state)

                val pos = parent.getChildAdapterPosition(view)
                when (pos) {
                    0 -> {
                        outRect.top = AndroidUtilities.dp(15f)
                        outRect.bottom = AndroidUtilities.dp(7f)
                    }
                    state.itemCount - 1 -> {
                        outRect.top =  AndroidUtilities.dp(7f)
                        outRect.bottom =  AndroidUtilities.dp(20f)

                    }
                    else -> {
                        outRect.bottom = AndroidUtilities.dp(7f)
                        outRect.top = AndroidUtilities.dp(7f)

                    }
                }
                outRect.left=AndroidUtilities.dp(15f)
                outRect.right=AndroidUtilities.dp(15f)

            }

        })
        layout.addView(recycleView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT))
        rootLayout.addView(layout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT))
        if (data != null && !data.isEmpty()) {
            list = data.toMutableList()
            list.add(RectF())
        }
        if (this::list.isInitialized) {
            adapter = RowListAdapter2(UserCarInfo::class.java, RowFactory { it -> WZDBComponent(it) })
            adapter.addFactory(RectF::class.java, { it -> WZDBComponent2(it) })
            adapter.items = list
            adapter.setOnItemClickedListener(UserCarInfo::class.java, { _, mode, _ ->

//                RouterUtils.getTargetIntent(context,RPaths.wzdbChooseCar)?.let {
//                    it.putExtra(Constants.EXTRA_DATA, mode)
//                    context.startActivity(it)
//                }

                (mode as? UserCarInfo)?.let {

                    QueryResultActivity.start(context,it,-1)
                }

                StatTools.sendClick(context, StatisticsId.clickWZDB_item)

            })
            adapter.setOnItemClickedListener(RectF::class.java, { _, _, _ ->
                if (adapter.itemCount >= 10){
                    ToastUtils.showText("超过汽车数量限制，请先删除其他车辆后再添加")
                }else{
                    RouterUtils.startAdd(context)
                    //AddEditLicenseActivity.startAdd(context, -1)

                }
            })
            recycleView.setHasFixedSize(true)
            recycleView.adapter = adapter
        }

    }

    fun onDestroy() {
        delegate?.onDestroy()
    }

    fun setupPage(){
        UserDataProvider.get().myCars(true)
                .subscribe(object : ProgressDialogObserver<List<UserCarInfo>>(context, "提示", "正在获取数据") {
                    override fun onApiResult(t: List<UserCarInfo>?) {
                        if (t == null || t.isEmpty()) {
                            showEmptyView()
                        } else {
                            showListLayout(t)
                        }
                    }

                    override fun onApiError(result: BaseResult<*>?) {
                        super.toastErrorMsg(result)
                    }
                })
    }
}